#include "Srv_Service_Handler.h"
#include "Srv_Asynch_Acceptor.h"
#include "Srv_Iocp_Deff.h"

Srv_Service_Handler::Srv_Service_Handler(SOCKET h,Srv_Asynch_Acceptor *pAsynch_Acceptor)
{
	m_client_socket		= h;
	m_pAsynch_Acceptor  = pAsynch_Acceptor;
}

Srv_Service_Handler::~Srv_Service_Handler( void )
{

}
void Srv_Service_Handler::Open()
{
	ReadRequest();
}

void Srv_Service_Handler::close()
{

}
Srv_Asynch_Acceptor * Srv_Service_Handler::Asynch_Acceptor()
{
	return m_pAsynch_Acceptor;
}

SOCKET Srv_Service_Handler::socket() const
{
	return m_client_socket;
}

bool Srv_Service_Handler::ReadRequest() const
{
	IOCP_OVERLAPPEDPLUS *olp = new IOCP_OVERLAPPEDPLUS; 

	memset(olp, 0, sizeof(IOCP_OVERLAPPEDPLUS)); 

	olp->client_socket = socket();

	olp->wbuf.buf = olp->buf;  

	olp->wbuf.len = sizeof(olp->buf);

	olp->OpCode = ENUM_REQUEST_READ; 

	int ret = WSARecv(olp->client_socket, &olp->wbuf, 1, &olp->wbuf.len, &olp->dwFlags, &olp->ol, NULL);  
	if (ret == SOCKET_ERROR)  
	{
		if (WSAGetLastError() != ERROR_IO_PENDING) 
			return false;
			
		return true;
	}

	return true;

}

bool Srv_Service_Handler::WriteRequest(const  char *pBuffr,int size ) const
{
	IOCP_OVERLAPPEDPLUS *olp = new IOCP_OVERLAPPEDPLUS; 

	memset(olp, 0, sizeof(IOCP_OVERLAPPEDPLUS));  

	memcpy(olp->buf,pBuffr,size);

	olp->client_socket = socket();

	olp->wbuf.buf = olp->buf;  

	olp->wbuf.len = size;

	olp->OpCode = ENUM_REQUEST_WRITE; 

	int ret = WSASend(olp->client_socket, &olp->wbuf, 1, &olp->wbuf.len, olp->dwFlags, &olp->ol, NULL);  
	if (ret == SOCKET_ERROR)  
	{
		if (WSAGetLastError() != ERROR_IO_PENDING) 
			return false;

			return true;
	}

	return true;
}
